//
//  NSDictionary+SortWithKey.m
//  JinliWallet
//
//  Created by 张玮 on 2018/10/17.
//  Copyright © 2018年 张玮. All rights reserved.
//

#import "NSDictionary+SortWithKey.h"
#import "NSString+Hash.h"

@implementation NSDictionary (SortWithKey)


#pragma mark - 按KEY排序
-(NSString *)stringSortedWithKey{
    
    NSMutableArray *keyArray = [[self allKeys] mutableCopy];
    [keyArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSComparisonResult result = [obj1 compare:obj2];
        return result;
    }];
    
    NSMutableString *resultString = [NSMutableString string];
    for (NSString *obj in keyArray) {
        if ([keyArray firstObject] != obj) {
            [resultString appendString:@"&"];
        }
        [resultString appendFormat:@"%@=%@",obj,self[obj]];
    }
    
    return resultString;
}

#pragma mark - 排序后执行Url Encode
-(NSString *)stringSortedWithKeyAndUrlEncode{
    NSString *temp = [self stringSortedWithKey];
    NSString *result = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil,
            (CFStringRef)temp, nil, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    return result;
}

#pragma mark - 最后执行HMAC-SHA1加密算法，输出Base64字符串，最后执行MD5加密
//-(NSString *)stringSortedWithKeyAndHash{
//    NSString *temp = [self stringSortedWithKeyAndUrlEncode];
//
//    NSLog(@"===== sign 1: %@ " , temp);
//    temp = [temp hmacSHA1StringWithKeyBase64:APP_SECT_KEY].md5String;
//
//    NSLog(@"===== sign 2: %@ " , temp);
//    return temp;
//}

@end
